package com.skyz.base.recyclerView;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class LinearSpacingItemDecoration extends RecyclerView.ItemDecoration {
    private final int leftRight;
    private final int topBottom;
    private final boolean includeEdge;

    public LinearSpacingItemDecoration(int leftRight, int topBottom) {
        this(leftRight, topBottom, false);
    }

    public LinearSpacingItemDecoration(int leftRight, int topBottom, boolean includeEdge) {
        this.leftRight = leftRight;
        this.topBottom = topBottom;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) {

        if (parent.getLayoutManager() instanceof LinearLayoutManager) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();

            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                if (includeEdge) {
                    if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                        outRect.bottom = topBottom;
                    }
                    outRect.top = topBottom;
                } else {
                    if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                        outRect.bottom = 0;
                    } else {
                        outRect.bottom = topBottom;
                    }
                }
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                if (includeEdge) {
                    if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                        outRect.right = leftRight;
                    }
                    outRect.left = leftRight;
                } else {
                    if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                        outRect.right = 0;
                    } else {
                        outRect.right = leftRight;
                    }
                }
                outRect.top = topBottom;
                outRect.bottom = topBottom;
            }
        }
    }
}
